package com.duang.framework.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

public class DB {

	private final Connection connection;
	private PreparedStatement preparedStatement;
	private ResultSet resultSet;

	private DB(DataSource dataSource) throws SQLException {
		this.connection = dataSource.getConnection();
	}

	public PreparedStatement getPreparedStatement(String sql)
			throws DuangDaoException {
		checkNotNull(this.preparedStatement);
		try {
			this.preparedStatement = this.connection.prepareStatement(sql);
		} catch (SQLException e) {
			throw new DuangDaoException(e);
		}
		return this.preparedStatement;

	}

	public boolean executeUpdate(String sql, Object... args) {
		return ExcuteSQLUtils.executeUpdate(getPreparedStatement(sql), args);
	}

	public void close() throws DuangDaoException {
		ExcuteSQLUtils.close(this.connection, this.preparedStatement,
				this.resultSet);
	}

	void checkNotNull(ResultSet rs) throws DuangDaoException {
		ExcuteSQLUtils.close(rs);
	}

	void checkNotNull(PreparedStatement ps) throws DuangDaoException {
		ExcuteSQLUtils.close(ps);
	}

	public ResultSet getResultSet(String sql, Object... args)
			throws DuangDaoException {
		PreparedStatement ps = getPreparedStatement(sql);
		checkNotNull(this.resultSet);
		this.resultSet = ExcuteSQLUtils.getResultSet(ps, sql, args);
		return this.resultSet;
	}

	public void commit() throws DuangDaoException {
		try {
			this.connection.commit();
			this.connection.setAutoCommit(true);
		} catch (SQLException e) {
			throw new DuangDaoException(e);
		}

	}

	public void closeTransaction() throws DuangDaoException {
		try {
			this.connection.setAutoCommit(true);
		} catch (SQLException e) {
			new DuangDaoException(e);
		}
	}

	public void openTransaction() throws DuangDaoException {
		try {
			this.connection.setAutoCommit(false);
		} catch (SQLException e) {
			new DuangDaoException(e);
		}
	}

	public static DB openDB(DataSource dataSource) throws DuangDaoException {
		try {
			return new DB(dataSource);
		} catch (SQLException e) {
			new DuangDaoException(e);
		}
		return null;
	}

	public void rollback() throws DuangDaoException {
		try {
			this.connection.rollback();
		} catch (SQLException e) {
			throw new DuangDaoException(e);
		}
	}

}
